package com.ibigcat.module.infra.controller.admin.file;

import com.ibigcat.framework.common.pojo.CommonResult;
import com.ibigcat.framework.common.util.object.BeanUtils;
import com.ibigcat.module.infra.controller.admin.file.vo.file.ChunkUploadRequest;
import com.ibigcat.module.infra.controller.admin.file.vo.file.FileRespVO;
import com.ibigcat.module.infra.controller.admin.file.vo.file.MergeChunkRequest;
import com.ibigcat.module.infra.service.file.BigFileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

import static com.ibigcat.framework.common.pojo.CommonResult.success;

/**
 * 大文件上传
 *
 * @author
 */
@RestController
@RequestMapping("/infra/chunk")
public class BigFileUploadController {

    @Resource
    private BigFileUploadService bigFileUploadService;

    /**
     * 检查文件状态(用于断点续传)
     * @param request
     * @return
     */
    @PostMapping("/check/{fileHash}")
    public CommonResult<Map<String, Object>> checkFileStatus(@PathVariable String fileHash,
                                                             HttpServletRequest request) {
        if (fileHash == null) {
            throw new IllegalArgumentException("参数异常");
        }

        Map<String, Object> result = bigFileUploadService.checkFileStatus(fileHash);
        return success(result);
    }

    /**
     * 上传分片文件
     * @param chunkFile
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public CommonResult<Boolean> uploadChunk(@RequestPart("chunk") MultipartFile chunkFile,
                                             @Valid ChunkUploadRequest chunkUploadRequest,
                                             HttpServletRequest request) {


        Boolean result = bigFileUploadService.uploadChunk(chunkUploadRequest, chunkFile);
        return success(result);
    }

    /**
     * 合并分片文件
     * @param mergeChunkRequest
     * @param request
     * @return
     */
    @PostMapping("/merge")
    public CommonResult<String> mergeChunks(@Valid @RequestBody MergeChunkRequest mergeChunkRequest,
                                            HttpServletRequest request) {
        String result = bigFileUploadService.mergeChunks(mergeChunkRequest);
        return success(result);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除文件")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteFile(@RequestParam("path") String path) throws Exception {
        bigFileUploadService.deleteFile(path);
        return success(true);
    }
}
